<template>
  <TopNavBar :title="_t18('21_pledge_order_record')" @rightClick="handleRightClick" type="back" />
  <div class="order-detail-page">
    <div class="order-tabs">
      <div :class="['tab', { active: activeTab === 'current' }]" @click="selectActive('current')">
        {{ _t18('21_current_position') }}
      </div>
      <div :class="['tab', { active: activeTab === 'history' }]" @click="selectActive('history')">
        {{ _t18('21_history_position') }}
      </div>
    </div>

    <!-- ✅ 当前持仓 -->
    <div v-if="activeTab === 'current'">
      <div v-if="currentOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('21_no_record') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in currentOrders" :key="idx" class="order-card current">
          <div class="order-card-header">
            <span class="pair">{{ order.coinSymbol?.toUpperCase() }}/USDT</span>

            <!-- 看涨看跌 -->
            <span class="tag up" v-if="order.betContent == 0"><span class="arrow">↓</span> {{ _t18('21_fall') }}</span>
            <span class="tag down" v-if="order.betContent == 1"><span class="arrow">↑</span> {{ _t18('21_rise') }}</span>

            <span v-if="Number(order.status) === 0" class="status">{{ _t18('21_holding') }}</span>
          </div>

          <div class="order-card-body">
            <div class="row"><span class="label">{{ _t18('21_open_time') }}</span><span class="value">{{ order.createTime }}</span></div>
            <div class="row"><span class="label">{{ _t18('21_open_price') }}</span><span class="value">{{ Number(order.openPrice) }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_open_value') }}</span><span class="value">{{ Number(order.openPrice) }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_buy_amount') }}</span><span class="value">{{ order.betAmount }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_profit_rate') }}</span><span class="value">{{ order.rate * 100 }}%</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- ✅ 历史订单 -->
    <div v-if="activeTab === 'history'">
      <div v-if="historyOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('21_no_record') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in historyOrders" :key="idx" class="order-card history">
          <div class="order-card-header">
            <span class="pair">{{ order.coinSymbol?.toUpperCase() }}/USDT</span>

            <!-- 看涨看跌 -->
            <span class="tag up" v-if="order.betContent == 0"><span class="arrow">↓</span> {{ _t18('21_fall') }}</span>
            <span class="tag down" v-if="order.betContent == 1"><span class="arrow">↑</span> {{ _t18('21_rise') }}</span>

            <!-- 状态 -->
            <span v-if="Number(order.status) === 0" class="status">{{ _t18('21_holding') }}</span>
            <span v-else-if="Number(order.status) === 1" class="status done">{{ _t18('21_done') }}</span>
            <span v-else-if="Number(order.status) === 2" class="status cancel">{{ _t18('21_cancel') }}</span>
            <span v-else-if="Number(order.status) === 3" class="status pending">{{ _t18('21_settling') }}</span>
          </div>

          <div class="order-card-body">
            <div class="row"><span class="label">{{ _t18('21_open_time') }}</span><span class="value">{{ order.createTime }}</span></div>
            <div class="row"><span class="label">{{ _t18('21_open_price') }}</span><span class="value">{{ Number(order.openPrice) }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_open_value') }}</span><span class="value">{{ Number(order.openPrice) }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_buy_amount') }}</span><span class="value">{{ order.betAmount }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('21_profit_rate') }}</span><span class="value">{{ order.rate }}%</span></div>

            <!-- ✅ 平仓價格 -->
            <div class="row">
              <span class="label">{{ _t18('21_close_price') }}</span>
              <span class="value" :class="{ waiting: [0, 3].includes(Number(order.status)) }">
                <template v-if="[0,3].includes(Number(order.status))">{{ _t18('21_pending_settle') }}</template>
                <template v-else>{{ order.closePrice }} USD</template>
              </span>
            </div>

            <!-- ✅ 平仓价值 -->
            <div class="row">
              <span class="label">{{ _t18('21_close_value') }}</span>
              <span class="value" :class="{ waiting: [0, 3].includes(Number(order.status)) }">
                <template v-if="[0,3].includes(Number(order.status))">{{ _t18('21_pending_settle') }}</template>
                <template v-else>{{ order.closePrice }} USD</template>
              </span>
            </div>

            <div class="row"><span class="label">{{ _t18('21_close_time') }}</span><span class="value">{{ order.closeTime }}</span></div>

            <!-- ✅ 獲利 -->
            <div class="row">
              <span class="label">{{ _t18('21_profit') }}</span>
              <span
                class="value"
                :class="{
                  waiting: [0,3].includes(Number(order.status)),
                  profit: order.rewardAmount - order.betAmount > 0 && ![0,3].includes(Number(order.status)),
                  loss: order.rewardAmount - order.betAmount < 0 && ![0,3].includes(Number(order.status))
                }"
              >
                <template v-if="[0,3].includes(Number(order.status))">{{ _t18('21_pending_settle') }}</template>
                <template v-else>
                  {{ order.rewardAmount - order.betAmount > 0 ? '+' : '-' }}
                  {{ Math.abs(order.rewardAmount - order.betAmount).toFixed(2) }} USD
                </template>
              </span>
            </div>

            <div class="row"><span class="label">{{ _t18('21_fee') }}</span><span class="value">0 USD</span></div>
          </div>

          <button class="detail-btn" @click="goToDetail(order.id)">{{ _t18('21_detail') }}</button>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { secondContractOrderselectOrderList } from '@/api/trade/index'

const router = useRouter()
const activeTab = ref('current')
const currentOrders = ref([])
const historyOrders = ref([])

function formatTime(value) {
  if (!value) return '-'
  const date = new Date(value)
  if (isNaN(date.getTime())) return value
  const yyyy = date.getFullYear()
  const MM = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')
  return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`
}

const getList = async (status) => {
  try {
    const res =
      status === 0
        ? await secondContractOrderselectOrderList({ status, aiType: '1' })
        : await secondContractOrderselectOrderList({ aiType: '1' })
    if (res.code === 200) {
      const data = res.data.map(i => ({
        ...i,
        status: Number(i.status ?? 0),
        createTime: formatTime(i.createTime),
        closeTime: formatTime(i.closeTime)
      }))
      status === 0 ? (currentOrders.value = data) : (historyOrders.value = data)
    }
  } catch (e) {}
}

function selectActive(val) {
  activeTab.value = val
  getList(val === 'current' ? 0 : 1)
}

function goToDetail(id) {
  router.push({ path: '/quantContractOrderDetail', query: { id } })
}

onMounted(() => getList(0))
</script>

<style scoped>
.order-detail-page {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 24px 0 0 0;
}
.order-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-radius: 999px;
  margin: 0 auto 32px auto;
  width: 90%;
  max-width: 380px;
  height: 52px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 4px;
}
.tab {
  flex: 1;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
  border-radius: 999px;
  color: #333;
  cursor: pointer;
  transition: all 0.25s ease;
}
.tab.active {
  background: #000;
  color: #fff;
  font-weight: 700;
}
.order-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 20px 18px 16px 18px;
  margin: 0 auto 16px auto;
  width: 90%;
  max-width: 380px;
}
.order-card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* ✅ 改为左对齐 */
  margin-bottom: 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  gap: 8px; /* ✅ 增加间距 */
}

.order-card-header .pair {
  font-size: 16px;
  font-weight: 700;
  color: #111;
  margin-right: 6px;
}

.order-card-header .status {
  margin-left: auto; /* ✅ 状态保持在最右侧 */
  font-size: 14px;
  font-weight: 700;
  color: #00c693;
}


.order-card-header .status {
  font-size: 14px;
  font-weight: 700;
  color: #00c693;
}
.order-card-header .status.pending { color: #ffaa00; }
.order-card-header .status.cancel { color: #999; }

.order-card-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
  line-height: 1.6;
}
.row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}
.label {
  color: #666;
}
.value {
  color: #222;
  font-weight: 600;
}
.value.profit { color: #00c693; font-weight: 700; }
.value.loss { color: #fa190c; font-weight: 700; }
.value.waiting { color: #999; font-weight: 500; }

.detail-btn {
  display: block;
  width: 90%;
  margin: 16px auto 0 auto;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
}
.detail-btn:hover { background: #222; }

.empty-box {
  margin: 100px auto 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.empty-icon {
  width: 110px;
  height: 110px;
  margin-bottom: 20px;
}
.empty-text {
  font-size: 14px;
  color: #889;
}
.tag {
  font-size: 11px;
  color: #fff;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 8px 24px 8px 8px;
  height: 17px;
  line-height: 17px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  gap: 2px;
}
.tag.up { background: #fa190c; }
.tag.down { background: #00c693; }
.arrow { font-size: 13px; font-weight: 700; }
</style>
